#include<rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>
#include<turtlesim/msg/pose.hpp>

using std::placeholders::_1;

class TopicSubscriber01 : public rclcpp::Node
{
    public:
    TopicSubscriber01(std::string name) : Node(name),last_print_time_(this->now())//初始化上次打印时间
    {

        RCLCPP_INFO(this->get_logger(),"你好！我是%s",name.c_str());

        pose_subscription_=this->create_subscription<turtlesim::msg::Pose>(
                "/turtle1/pose",//这个是要订阅的话题名称
                10,//QoS队列大小
                std::bind(&TopicSubscriber01::pose_callback,this,_1)//回调


        );

        RCLCPP_INFO(this->get_logger(),"你好！我是%s,我已经订阅turtlesim的pose话题！",name.c_str());

    }

    private:
     // 确保回调函数有正确的参数类型
    void pose_callback(const turtlesim::msg::Pose::SharedPtr msg)
    {
        auto now =this->now();
        //计算与上次打印的时间差(如果间隔大于1秒，就打印)
        double time_since_last_print=(now-last_print_time_).seconds();

        if(time_since_last_print>=1.0){
            RCLCPP_INFO(this->get_logger(), 
                   "乌龟位置 - X: %.2f, Y: %.2f, 角度: %.2f",
                   msg->x, msg->y, msg->theta);
             last_print_time_= now;
        }
        
    }
    
    //声明
    rclcpp::Time last_print_time_;
    rclcpp::Subscription<turtlesim::msg::Pose>::SharedPtr pose_subscription_;


};


int main(int argc, char ** argv){
    rclcpp ::init(argc,argv);
     /*创建对应节点的共享指针对象*/
     auto node =std::make_shared<TopicSubscriber01>("topic_subscriber_01");
    /*调用构造函数*/
    rclcpp::spin(node);
    rclcpp::shutdown();
     /* 运行节点，并检测退出信号*/
    return 0;
}